﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Security.Principal;
using System.Xml.Linq;
using COM.Data;

namespace COM.Service
{
    /// <summary>
    /// 用于角色类型/角色名称的转换
    /// </summary>
    public interface IPermissionRoleListService
    {
        IPermissionRoleListService RegisterRoleType<T>() where T : PermissionRole;
        string GetRoleNameByType<T>() where T : PermissionRole;
        Type GetRoleTypeByName(string roleName);
    }

    public class PermissionRoleListService : IPermissionRoleListService
    {
        private List<Type> roleTypeList;
        private List<Type> RoleTypeList
        {
            get
            {
                return this.roleTypeList ?? (this.roleTypeList = new List<Type>());
            }
        }

        private Dictionary<string, Type> roleNameTypeDict;
        private Dictionary<string, Type> RoleNameTypeDict
        {
            get
            {
                if (this.roleNameTypeDict == null)
                {
                    this.roleNameTypeDict = this.RoleTypeList.Select(t => new { name = (Activator.CreateInstance(t) as PermissionRole).EnumRoleName, type = t }).ToDictionary(i => i.name, i => i.type);
                }
                return this.roleNameTypeDict;
            }
        }

        private Dictionary<Type, string> roleTypeNameDict;
        private Dictionary<Type, string> RoleTypeNameDict
        {
            get
            {
                if (this.roleTypeNameDict == null)
                {
                    this.roleTypeNameDict = this.RoleTypeList.Select(t => new { name = (Activator.CreateInstance(t) as PermissionRole).EnumRoleName, type = t }).ToDictionary(i => i.type, i => i.name);
                }
                return this.roleTypeNameDict;
            }
        }

        
        public Type GetRoleTypeByName(string roleName)
        {
            if (this.RoleNameTypeDict.ContainsKey(roleName))
                return this.RoleNameTypeDict[roleName];
            else
                return null;
        }

        public string GetRoleNameByType<T>() where T : PermissionRole
        {
            var t = typeof(T);
            if (!this.RoleTypeNameDict.ContainsKey(t))
                throw new ApplicationException(string.Format("角色{0}未注册", t.FullName));
            return this.RoleTypeNameDict[t];
        }

        public IPermissionRoleListService RegisterRoleType<T>() where T : PermissionRole
        {
            this.RoleTypeList.Add(typeof(T));
            this.roleNameTypeDict = null;
            this.roleTypeNameDict = null;
            return this;
        }

    }

}


